package com.alogic.xscript.ldap;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.*;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.naming.NamingException;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import java.util.ArrayList;
import java.util.List;

/**
 * 增加ldap条目
 */
public class LDAPAdd extends LDAPConnection.Operation{

    protected static final String OBJ_CLASS_DEFAULT = "account";
    /**
     * 条目的对象类型，可以指定多个对象类，以逗号分隔，缺省为account
     */
    protected String $objClazz = OBJ_CLASS_DEFAULT;

    /**
     * 新增条目的dn
     */
    protected String $dn;

    /**
     * 条目的初始化属性
     */
    protected List<Pair<String,String >> attrList = new ArrayList<Pair<String,String>>();

    /**
     * 结果id
     */
    protected String id;

    /**
     * 如果存在是否覆盖
     */
    protected boolean overwrite = false;

    public LDAPAdd(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $objClazz = PropertiesConstants.getRaw(p,"objClass",$objClazz);
        $dn = PropertiesConstants.getRaw(p,"dn",$dn);

        id = PropertiesConstants.getString(p,"id","",true);
        overwrite = PropertiesConstants.getBoolean(p,"overwrite",overwrite,true);
    }

    @Override
    public void configure(Element e, Properties p) {
        Properties props = new XmlElementProperties(e,p);
        configure(props);

        NodeList nodeList = XmlTools.getNodeListByPath(e, "attr");
        for (int i = 0 ;i < nodeList.getLength() ; i ++){
            Node n = nodeList.item(i);
            if (n.getNodeType() != Node.ELEMENT_NODE){
                continue;
            }

            Element elem = (Element)n;
            String id = elem.getAttribute("id");
            String value = elem.getAttribute("value");
            if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(value)){
                attrList.add(new Pair.Default<String,String>(id,value));
            }
        }
    }

    @Override
    protected void onExecute(DirContext dirContext, XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String dn = PropertiesConstants.transform(ctx,$dn,"");
        if (StringUtils.isEmpty(dn)){
            log("The dn is null,operation is ignored.",LOG_ERROR,ctx);
            return ;
        }

        try {
            Object exist = dirContext.lookup(dn);
            if (exist != null){
                // 条目已存在
                if (overwrite) {
                    BasicAttributes attrs = new BasicAttributes();
                    BasicAttribute objclassSet = new BasicAttribute("objectClass");
                    String objClazz = PropertiesConstants.transform(ctx,$objClazz,OBJ_CLASS_DEFAULT);
                    String [] clazz = objClazz.split(",");
                    for (String item:clazz){
                        if (StringUtils.isNotEmpty(item)){
                            objclassSet.add(item);
                        }
                    }
                    attrs.put(objclassSet);
                    for (Pair<String,String> pair:attrList){
                        String key = pair.key();
                        String value = ctx.transform(pair.value());
                        if (StringUtils.isNotEmpty(value)){
                            attrs.put(key,value);
                        }
                    }
                    dirContext.destroySubcontext(dn);
                    dirContext.createSubcontext(dn,attrs);
                }else{
                    BasicAttributes attrs = new BasicAttributes();
                    for (Pair<String,String> pair:attrList){
                        String key = pair.key();
                        String value = ctx.transform(pair.value());
                        if (StringUtils.isNotEmpty(value)){
                            attrs.put(key,value);
                        }
                    }
                    dirContext.modifyAttributes(dn,DirContext.REPLACE_ATTRIBUTE,attrs);
                }
            }else{
                BasicAttributes attrs = new BasicAttributes();
                BasicAttribute objclassSet = new BasicAttribute("objectClass");
                String objClazz = PropertiesConstants.transform(ctx,$objClazz,OBJ_CLASS_DEFAULT);
                String [] clazz = objClazz.split(",");
                for (String item:clazz){
                    if (StringUtils.isNotEmpty(item)){
                        objclassSet.add(item);
                    }
                }
                attrs.put(objclassSet);
                for (Pair<String,String> pair:attrList){
                    String key = pair.key();
                    String value = ctx.transform(pair.value());
                    if (StringUtils.isNotEmpty(value)){
                        attrs.put(key,value);
                    }
                }
                dirContext.createSubcontext(dn,attrs);
            }

            if (StringUtils.isNotEmpty(id)){
                ctx.SetValue(id,"true");
            }
        }catch (NamingException ex){
            log("Can not create dir context:" + ex.toString(),LOG_ERROR,ctx);
            if (StringUtils.isNotEmpty(id)){
                ctx.SetValue(id,ex.getClass().getName());
                ctx.SetValue(id + ".reason",ex.toString(true));
            }
        }
    }
}
